layui.define(['layer', 'table','element', 'form','jquery'],function(exports) {
    var layer = layui.layer //弹层
        ,table = layui.table //表格
        ,element = layui.element //元素操作
        ,$ = layui.jquery

        ,form = layui.form;


    departmentPage = {

        //部门表格初始化
        init_department_table: function () {
                department_table_Info = table.render({
                elem: '#department_table', //选取html表格的id
                id: 'department_table_Id',
                response: {
                    statusCode: '200 ' //规定成功的状态码，默认：0
                }
                ,url: '/manage/department'
                ,title: '商品表'
                ,toolbar: '#department_table_top'
                ,page: true
                ,cols: [[
                    {type: 'checkbox', fixed: 'left'}
                    ,{field: 'departmentName', title: '名称', align:'center',sort: true, fixed: 'left'}
                    ,{field: 'type', title: '类型 ', align:'center',sort: true, fixed: 'left',templet: function (row){
                            var type = row.type;
                            if (type===0){
                                return "上架商品"
                            } else if (type===1) {
                                return "下架商品"
                            }else {
                                return "--"
                            }
                        }}
                    ,{field: 'pname', title: '直属', align:'center',sort: true, fixed: 'left'}
                    ,{field: 'departmentNumber', title: '编号', align:'center',sort: true, fixed: 'left'}
                    ,{field: 'status', title: '状态', align:'center' , event:  'change_status',fixed: 'left',templet: function (row){
                            var status = row.status;
                            var rowData = JSON.stringify(row);
                            switch (status) {
                                case 0:
                                    return '<input type="checkbox" row-data=\''+ rowData + '\' name="status"  lay-skin="switch" lay-filter="department_table_Switch" lay-text="启用|禁用" >';
                                case 1:
                                    return '<input type="checkbox" row-data=\''+ rowData + '\' name="status" checked lay-skin="switch" lay-filter="department_table_Switch" lay-text="启用|禁用" > ';
                                default:
                                    return '<input type="checkbox" row-data=\''+ rowData + '\' name="status"    lay-skin="switch" lay-filter="department_table_Switch" lay-text="启用|禁用" >' ;
                            }
                        }}
                    ,{field: 'createTime', title: '创建时间', align:'center' , fixed: 'left'}
                    ,{fixed: 'tool', title: '操作',width: 165, align:'center', toolbar: '#department_table_right'}
                ]]
                ,where:{
                    type: 0
                }
            });


        },

        //监听表格行工具事件   tool是行工具条
        init_listen_table_tool(){
            table.on('tool(department_table)', function(obj){ //注：tool 是工具条事件名，demo 是 table 原始容器的属性 lay-filter="对应的值"
                var data = null;
                data = obj.data;     //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值
                if(layEvent === 'detail_department'){
                }
                else if(layEvent === 'delete_department'){
                    //部门单行删除
                    departmentPage.delete_department(data);
                }
                else if(layEvent === 'edit_department'){
                    //部门编辑
                    departmentPage.init_department_form('edit', data);
                }
                // departmentPage.listen_department_table_switch(obj)
            });
        },

        //监听表格头工具条事件 toolbar是头工具条
        init_listen_table_toolbar(){
            table.on('toolbar(department_table)', function(obj){
                var checkStatus = table.checkStatus("department_table_Id") //department_table_Id来自layui 初始化表格ID
                    ,choose_data = checkStatus.data; //获取选中的数据
                switch(obj.event){
                    case 'add_department':
                        departmentPage.init_department_form('add','');
                        break;
                    case 'batch_department_deleted':
                        departmentPage.batch_delete_department(choose_data);
                        break;
                }
            });
        },

        //打开新增/编辑弹框，这一层主要负责是否给编辑框赋值--->打开弹出层参数 type 类型 ,data 编辑改行的数据
        init_department_form: function (type,data){
            var form_title = '';
            type === 'add' ? form_title = "添加部门" :  form_title ="编辑部门";
            $.get('/manage/form/edit_department.html', function (html) {
                nowIndex = layer.open(  //弹出层
                    {
                        type: 1,
                        title: form_title,
                        area: ['500px', '450px'],
                        btnAlign: 'c',//按钮居中对齐
                        content:  html,
                        anim: 5,//弹出效果 渐显
                        shift: -1,
                        btn: ['保存','关闭'],
                        yes: function(){
                            departmentPage.update_form(type,data);
                        },
                        btn2:function(){},
                        success:function(){
                            if (type === 'edit'){
                                $("#departmentName").val(data.departmentName);
                                $("#parentId").val(data.parentId);
                                $("#departmentNumber").val(data.departmentNumber);
                                var form_type = data.type;
                                form_type === 0 ? form_type =true:form_type = false;// 部门？ true : false

                                $('#rdoPartment').attr("checked", form_type);
                                $('#rdoRoom').attr("checked", !form_type);

                                var status = data.status;
                                status === 1 ? status = true :status = false;
                                $("#status").prop("checked",status);
                                departmentPage.init_parent_dept_form(data.parentId);

                            }
                            else {
                                departmentPage.init_parent_dept_form();
                            }
                            layui.form.render();
                        },

                    });
            })
        },

        // 表格页面监听表单中的switch改变发送请求
        listen_department_table_switch: function() {
            //监听行单击事件
            form.on('switch(department_table_Switch)', function(data){
                var switch_status = data.elem.checked?1:0;
                var row_data = JSON.parse( data.elem.getAttribute('row-data'));
                $.ajax({
                    url: "/manage/department/" + row_data.departmentId,
                    contentType : "application/json",
                    type: 'PUT',
                    data:JSON.stringify( {status:switch_status}),
                    success: function (resp) {
                        if (resp.code===200){
                            var data = resp.data;
                            layer.msg('保存成功', {icon: 1});
                            department_table_Info.reload();
                        }else {
                            layui.form.render();
                            layer.msg("保存失败"+ " "+ resp.msg, {icon: 5});
                        }

                    }
                });

            });



        },

        //表单新增/编辑  新增就提交表单，编辑就赋值表单等待表单提交
        update_form:function(type,data){
            // 请求方式处理和URL处理
            if (type==='add'){
                request_method = 'POST';
                request_url = '/manage/department';
            }else {
                request_method = 'PUT';
                request_url = '/manage/department/'+ data.departmentId;
            }
            var status =  $("#status").prop("checked");
            status ? status = 1 :status =0;
            var department_form_data = {
                departmentName: $("#departmentName").val(),
                type: $('input[name="department_type"]:checked').val(),
                parentId: $("#parentId").val(),
                departmentNumber: $("#departmentNumber").val(),
                status:  status ,
            };
            $.ajax({
                url: request_url,
                contentType : "application/json",
                type: request_method,
                data:JSON.stringify(department_form_data,),
                success: function (resp) {
                    if (resp.code===200){
                        var data = resp.data;
                        layer.msg('保存成功', {icon: 1});
                        layer.close(nowIndex);
                        department_table_Info.reload();
                    }else {
                        layui.form.render();
                        layer.msg("保存失败"+ " "+ resp.msg, {icon: 5});
                    }

                }
            });


        },

        //部门单行删除
        delete_department:function (data){
            layer.confirm("是否删除["+ data.departmentName +"]", function(index){
                $.ajax({
                    type: "DELETE",
                    contentType:"application/json",//设置请求参数类型为json字符串
                    url: "/manage/department/" + data.departmentId  ,
                    success:function(resp){
                        var code = resp.code;
                        if (code === 200 ){
                            layer.msg('删除成功', {icon: 1});
                            department_table_Info.reload();
                        }else {
                            layer.msg("删除失败 "+resp.msg , {icon: 5});
                        }
                    }
                });
                layer.close(index);
                //向服务端发送删除指令
            });
        },

        //部门批量删除 choose_data选中的行数据
        batch_delete_department:function (choose_data) {
            if(choose_data.length === 0){
                layer.msg('请选择一行');
            } else {
                var keyArr = '';
                var nameArr = '';
                $.each(choose_data,function (index, val) { //index是数组对象索引，val是对象
                    if (index===0){
                        keyArr = keyArr + val.departmentId;
                        nameArr = nameArr + val.departmentName;
                    }else {
                        keyArr = keyArr +','+ val.departmentId;
                        nameArr = nameArr +','+ val.departmentName;
                    }
                });

                layer.confirm('是否确定删除选中的数据['+ nameArr +"]",
                    {
                        icon:0,
                        title: "提示",
                        skin: "deleteTips"
                    }
                    , function(){
                        $.ajax({
                            type: "POST",
                            contentType:"application/x-www-form-urlencoded",//设置请求参数类型为json字符串
                            url: "/manage/department/batchDepartment",
                            data:{
                                ids: keyArr ,
                                nameArr: nameArr
                            },
                            success:function(resp){
                                var code = resp.code;
                                if (code === 200 ){
                                    layer.msg('删除成功', {icon: 1});
                                    department_table_Info.reload();
                                }else {
                                    layer.msg("删除失败", {icon: 5});
                                }
                            }
                        });


                    });
            }
        },

        // 初始化父级部门
        init_parent_dept_form:function (select_parent_id) {
            $.ajax({
                type: "GET",
                contentType:"application/json",
                url: "/manage/department/findParentDept",
                success:function(resp){
                    var code = resp.code;
                    if (code === 200 ){
                        $.each(resp.data,function(index,item){
                            //option  第一个参数是页面显示的值，第二个参数是传递到后台的值
                            $('#parentId').append(new Option(item.departmentName,item.departmentId));//往下拉菜单里添加元素
                            //设置value（这个值就可以是在更新的时候后台传递到前台的值）为2的值为默认选中
                            if (select_parent_id!==undefined){
                                $('#parentId').val(select_parent_id);
                            }

                            form.render('select')
                        })
                    }else {
                        layer.msg("请求失败", {icon: 5});

                    }
                }
            });
        },

        //表格搜索条件
        listen_department_search:function(){
            $("#searchDept").click(function () {
                {
                    var searchType = $("#search_dept_type").val();
                    layui.table.reload("department_table_Id",{
                        where:{
                            type: searchType
                        }

                    })
                }
            });
        }
    };

    departmentPage.init_department_table();
    departmentPage.listen_department_table_switch();
    departmentPage.init_listen_table_tool();
    departmentPage.init_listen_table_toolbar();
    departmentPage.listen_department_search();
    exports("departmentPage",departmentPage);






});